<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,100分)- 最大括号深度（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>现有一字符串仅由 ‘(‘&#xff0c;’)’&#xff0c;&#39;{‘&#xff0c;’}’&#xff0c;&#39;[‘&#xff0c;’]’六种括号组成。</p> 
<p>若字符串满足以下条件之一&#xff0c;则为无效字符串&#xff1a;</p> 
<p>①任一类型的左右括号数量不相等&#xff1b;</p> 
<p>②存在未按正确顺序&#xff08;先左后右&#xff09;闭合的括号。</p> 
<p>输出括号的最大嵌套深度&#xff0c;若字符串无效则输出0。</p> 
<p>0≤字符串长度≤100000</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>一个只包括 ‘(‘&#xff0c;’)’&#xff0c;&#39;{‘&#xff0c;’}’&#xff0c;&#39;[‘&#xff0c;’]’的字符串</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>一个整数&#xff0c;最大的括号深度</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">[]</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">1</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">有效字符串&#xff0c;最大嵌套深度为1</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">([]{()})</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">3</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">有效字符串&#xff0c;最大嵌套深度为3</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">(]</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">0</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无效字符串&#xff0c;有两种类型的左右括号数量不相等</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">([)]</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">0</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无效字符串&#xff0c;存在未按正确顺序闭合的括号</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">)(</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">0</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无效字符串&#xff0c;存在未按正确顺序闭合的括号。</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题可以通过栈结构来判断括号的对称性。</p> 
<p>本题的难点在于最大深度计算&#xff0c;其实也不难&#xff0c;就是看是否形成了连续出栈</p> 
<p><img alt="" height="526" src="https://img-blog.csdnimg.cn/7ee7d136e27f4b96bced43839c02b703.png" width="1200" /></p> 
<p> 代码实现就是看入栈的一直是&#39;)&#39;&#xff0c;&#39;]&#39;&#xff0c;&#39;}&#39; &#xff0c;则意味着必然要出栈一对括号&#xff0c;则深度一直自增&#xff0c;如果入栈的是&#39;(&#39;&#xff0c;&#39;[&#39;&#xff0c;&#39;{&#39; &#xff0c;则意味着入栈元素不会和栈顶元素形成一队括号&#xff0c;也就不会出栈&#xff0c;此时深度重置为0</p> 
<p></p> 
<hr /> 
<p>2023.05.21 根据网友指正&#xff0c;上面求解最大深度有问题&#xff0c;我们不应该将连续出栈次数作为最大深度&#xff0c;这是有漏洞的&#xff0c;比如用例&#xff1a;</p> 
<blockquote> 
 <p>({[]}())</p> 
</blockquote> 
<p>其实&#xff0c;本题在stack栈中&#xff0c;一旦遇到闭合的括号就会弹出&#xff0c;因此stack栈中能保留的只是左括号&#xff0c;而我们可以直接将stack栈中保留的左括号的最大数量作为最大深度&#xff0c;而stack栈的本身size就是对应的左括号数量。</p> 
<p>比如下面图示中画红框的地方</p> 
<p><img alt="" height="525" src="https://img-blog.csdnimg.cn/fd426cd12d3f49e5834fefc790798d96.png" width="1200" /></p> 
<p> </p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  console.log(getMaxDepth(line));
});

function getMaxDepth(str) {
  const map &#61; {
    &#34;)&#34;: &#34;(&#34;,
    &#34;]&#34;: &#34;[&#34;,
    &#34;}&#34;: &#34;{&#34;,
  };

  const stack &#61; [];

  let maxDepth &#61; 0;
  for (let i &#61; 0; i &lt; str.length; i&#43;&#43;) {
    let c &#61; str[i];

    if (stack.length &gt; 0 &amp;&amp; map[c] &#61;&#61;&#61; stack.at(-1)) {
      stack.pop();
    } else {
      stack.push(c);
      maxDepth &#61; Math.max(maxDepth, stack.length);
    }
  }

  if (stack.length) return 0;
  return maxDepth;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
  // 输入获取
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    String s &#61; sc.nextLine();
    System.out.println(getResult(s));
  }

  // 算法入口
  public static int getResult(String s) {
    HashMap&lt;Character, Character&gt; map &#61; new HashMap&lt;&gt;();
    map.put(&#39;)&#39;, &#39;(&#39;);
    map.put(&#39;]&#39;, &#39;[&#39;);
    map.put(&#39;}&#39;, &#39;{&#39;);

    LinkedList&lt;Character&gt; stack &#61; new LinkedList&lt;&gt;();

    int maxDepth &#61; 0;
    for (int i &#61; 0; i &lt; s.length(); i&#43;&#43;) {
      char c &#61; s.charAt(i);

      if (stack.size() &gt; 0 &amp;&amp; map.get(c) &#61;&#61; stack.getLast()) {
        stack.removeLast();
      } else {
        stack.add(c);
        maxDepth &#61; Math.max(maxDepth, stack.size());
      }
    }

    if (stack.size() &gt; 0) return 0;
    return maxDepth;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
s &#61; input()


# 算法入口
def getResult():
    map &#61; {
        &#34;)&#34;: &#34;(&#34;,
        &#34;]&#34;: &#34;[&#34;,
        &#34;}&#34;: &#34;{&#34;
    }

    stack &#61; []

    maxDepth &#61; 0
    for i in range(len(s)):
        c &#61; s[i]

        if len(stack) &gt; 0 and map.get(c) is not None and map[c] &#61;&#61; stack[-1]:
            stack.pop()
        else:
            stack.append(c)
            maxDepth &#61; max(maxDepth, len(stack))

    if len(stack) &gt; 0:
        return 0

    return maxDepth


# 算法调用
print(getResult())</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>